package org.ncibi.cytoscape.metscape.task;

import java.util.Collection;

import org.ncibi.cytoscape.metscape.network.MetScapeNetworks;

import cytoscape.CyNetwork;
import cytoscape.Cytoscape;
import cytoscape.layout.CyLayoutAlgorithm;
import cytoscape.layout.CyLayouts;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;

public class BuildSubnetworkTask implements Task {

	
	private Collection<?> nodes;
	private Collection<?> edges;
	private String networkName;
	private CyNetwork network;

	private TaskMonitor taskMonitor;
	private boolean interrupted = false;

	public static void newSubnetwork(Collection<?> nodes,
			Collection<?> edges, String subnetworkName, CyNetwork network) {
		BuildSubnetworkTask task = new BuildSubnetworkTask(nodes, edges,
				subnetworkName, network);
		configureAndRunTask(task);
	}
	
	public BuildSubnetworkTask(Collection<?> nodes, Collection<?> edges,
			String networkName, CyNetwork network) {
		this.nodes = nodes;
		this.edges = edges;
		this.networkName = networkName;
		this.network = network;
	}
	
	private static void configureAndRunTask(BuildSubnetworkTask task) {
		// Configure JTask Dialog Pop-Up Box
		JTaskConfig jTaskConfig = new JTaskConfig();
		jTaskConfig.setOwner(Cytoscape.getDesktop());
		jTaskConfig.displayCancelButton(true);
		jTaskConfig.displayStatus(true);

		// Execute Task in New Thread; pops open JTask Dialog Box.
		TaskManager.executeTask(task, jTaskConfig);
	}

	public void setTaskMonitor(TaskMonitor monitor)
			throws IllegalThreadStateException {
		taskMonitor = monitor;
	}

	public void halt() {
		interrupted = true;
	}

	public String getTitle() {
		return "Build Subnetwork";
	}

	public void run() {
		try {
			taskMonitor.setPercentCompleted(-1);
			taskMonitor.setStatus("Building subnetwork...");
			CyNetwork subnetwork = MetScapeNetworks.buildSubnetwork(nodes, edges, networkName, network);
			if (subnetwork == null || interrupted)
				throw new Exception();
			CyLayoutAlgorithm layout = CyLayouts.getLayout("force-directed");
			layout.doLayout(Cytoscape.getCurrentNetworkView(), taskMonitor);
			
			taskMonitor.setStatus("Complete");
			taskMonitor.setPercentCompleted(100);

		} catch (Throwable t) {
			if (!interrupted)
				taskMonitor.setException(t, "Network build failed");
		}

	}
}
